﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using BartonExtension;
using System.Web.Script.Services;
using ResponseObject;
using SqlServerWrapper;
using System.Data.SqlClient;
using System.Data;
using Model;
using IntelligentRouteAssist;
using ZKCache;

namespace WebSrvs.NET
{
    /// <summary>
    /// ZK_ShoppingGuide 的摘要说明
    /// </summary>
    [System.Web.Script.Services.ScriptService]
    [WebService(Namespace = "http://zker.hk/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class ZK_ShoppingGuide : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet=true, ResponseFormat = ResponseFormat.Json)]
        public string GetSpotlights()
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using(SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = SqlCommandManager.Create(conn,CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_spotlights";
                    try
                    {
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("data");
                            dt.Load(dr);
                            if (dt.Rows.Count > 0)
                                response.userinfo = dt;
                            else
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_REQ_NO_RESULT;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_REQ_NO_RESULT;
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public string GetMustHaves()
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_must_have";
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("data");
                            dt.Load(dr);
                            if (dt.Rows.Count > 0)
                                response.userinfo = dt;
                            else
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_REQ_NO_RESULT;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_REQ_NO_RESULT;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public string GetFeatured()
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_featured";
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            DataTable dt = new DataTable("data");
                            dt.Load(dr);
                            if (dt.Rows.Count > 0)
                                response.userinfo = dt;
                            else
                            {
                                response.isProcessSuccess = false;
                                response.errCode = ErrorCodes.CODE_ERR_ON_REQ_NO_RESULT;
                                response.errMsg = ErrorMsgs.MSG_ERR_ON_REQ_NO_RESULT;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GenerateRoutePath(string budget,string brands,string catalogs,int line_type,string time_to_go,float lat,float lon,float low_brand,float top_brand)
        {
            float b = budget.Split(',')[1].toFloat().Value;

            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using(SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = SqlCommandManager.Create(conn,CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_generate_route";
                    cmd.Parameters.Add("@initial_loc_lat", SqlDbType.Float).Value = lat;
                    cmd.Parameters.Add("@initial_loc_lon", SqlDbType.Float).Value = lon;
                    cmd.Parameters.Add("@time_to_go", SqlDbType.VarChar).Value = time_to_go;
                    cmd.Parameters.Add("@budget", SqlDbType.Float).Value = b;
                    cmd.Parameters.Add("@brands", SqlDbType.VarChar).Value = brands;
                    cmd.Parameters.Add("@catalogs", SqlDbType.VarChar).Value = catalogs;
                    cmd.Parameters.Add("@line_type", SqlDbType.Int).Value = line_type;
                    cmd.Parameters.Add("@low_brand", SqlDbType.Float).Value = low_brand;
                    cmd.Parameters.Add("@top_brand", SqlDbType.Float).Value = top_brand;
                    try
                    {
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            List<RouteObj> results = new List<RouteObj>();
                            while(dr.Read())
                            {
                                RouteObj obj = new RouteObj()
                                {
                                    mall = new RouteMallObj()
                                    {
                                        mall_id = dr["mall_id"].toInt32().Value,
                                        mall_name = dr["mall_name"].ToString(),
                                        m_lat = dr["m_lat"].toFloat().Value,
                                        m_lon = dr["m_lon"].toFloat().Value,
                                        street = dr["street"].ToString(),
                                        region = dr["region"].ToString(),
                                        code = dr["code"].ToString(),
                                        mall_score = dr["mall_score"].toFloat().Value,
                                        mall_frequency = dr["mall_frequency"].toFloat().Value,
                                        spend_time_on_mall = dr["spend_time_on_mall"].toFloat().Value,
                                        distanceFromYou = dr["KiloMetersFromYou"].toFloat().Value
                                    },
                                    store = new RouteStoreObj()
                                    {
                                        store_id = dr["store_id"].toInt32().Value,
                                        store_title = dr["store_title"].ToString(),
                                        matched_catalog_ratio = dr["matched_catalog_ratio"].toFloat().Value,
                                        duration = dr["duration"].toFloat().Value,
                                        desc = dr["desc"].ToString(),
                                        tel = dr["tel"].ToString(),
                                        live_time = dr["live_time"].ToString(),
                                        store_sale_rate = dr["store_sale_rate"].toFloat().Value

                                    }
                                };
                                results.Add(obj);
                            }
                            response.userinfo = RouteGenerator.GenerateRoute(results, new ZTimeline()
                                {
                                    atHour = 8,
                                    atMin = 0
                                });
                        }
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string TestThumbnail()
        {
            ZKResponse response = new ZKResponse();
            string filename = "image_0.jpg";
            string path = Server.MapPath("..");
            bool done = ImageHelper.GenerateThumb(path, filename, 640, 960);
            response.isProcessSuccess = done;
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string RequestSale(SaleType sale_type,string req_data,int page_idx,int page_size)
        {
            ZKResponse response = new ZKResponse();
            string identifier = "{0}_{1}_{2}_{3}".FormatWith(sale_type,req_data,page_size,page_idx).toBase64();
            List<Dictionary<string, object>> results = CacheCore.standardCache.cacheWithIdentifier<List<Dictionary<string, object>>>(identifier);
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using(SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = SqlCommandManager.Create(conn,CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_req_sales";
                    cmd.Parameters.Add("@req_sale_type", SqlDbType.Int).Value = sale_type;
                    cmd.Parameters.Add("@req_data", SqlDbType.VarChar).Value = req_data;
                    cmd.Parameters.Add("@page_size", SqlDbType.Int).Value = page_size;
                    cmd.Parameters.Add("@page_idx", SqlDbType.Int).Value = page_idx;
                    try
                    {
                        results = new List<Dictionary<string, object>>();
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            while(dr.Read())
                            {
                                Dictionary<string, object> result = new Dictionary<string, object>();
                                for(int i=0;i<dr.FieldCount;i++)
                                {
                                    result.Add(dr.GetName(i), dr.GetValue(i));
                                }
                                if (!result["images"].ToString().isNullOrEmpty())
                                {
                                    string cover = result["images"].ToString().Split(',')[0] + ".jpg";
                                    int store_id = result["store_id"].toInt32().Value;
                                    int act_id = result[@"act_id"].toInt32().Value;
                                    string path = Server.MapPath("../data/images/activities/{0}/{1}".FormatWith(store_id,act_id));
                                    result.Add("thumb", ImageHelper.GenerateThumb(path, cover, 320,320));
                                    string imageFile = path + @"\" + cover;
                                    System.Drawing.Size size = ImageHelper.GetImageSize(imageFile);
                                    result.Add("image_width", size.Width);
                                    result.Add("image_height", size.Height);
                                }
                                results.Add(result);
                            }
                            CacheCore.standardCache.CreateCacheWithIdentifier(identifier, results,10);
                            response.userinfo = results;
                        }
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string RequestSaleInStore(int store_id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using(SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = SqlCommandManager.Create(conn,CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_sale_from_store";
                    cmd.Parameters.Add("@store_id", SqlDbType.Int).Value = store_id;
                    try
                    {
                        List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                Dictionary<string, object> result = new Dictionary<string, object>();
                                for (int i = 0; i < dr.FieldCount; i++)
                                {
                                    result.Add(dr.GetName(i), dr[i]);
                                }
                                results.Add(result);
                            }
                        }
                        response.userinfo = results;
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string RequestNearBySale(float lat, float lon, float distance)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_nearby_sale";
                    cmd.Parameters.Add("@lat", SqlDbType.Float).Value = lat;
                    cmd.Parameters.Add("@lon", SqlDbType.Float).Value = lon;
                    cmd.Parameters.Add("@distance", SqlDbType.Float).Value = distance;

                    try
                    {
                        List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                Dictionary<string, object> r = new Dictionary<string, object>();
                                for (int i = 0; i < dr.FieldCount; i++)
                                {
                                    r.Add(dr.GetName(i), dr.GetValue(i));
                                }
                                results.Add(r);
                            }
                        }
                        response.userinfo = results;
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string RequestSaleTimeline(string time_from,string time_to)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using(SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = SqlCommandManager.Create(conn,CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_activity_timeline";
                    cmd.Parameters.Add("@time_from", SqlDbType.VarChar).Value = time_from;
                    cmd.Parameters.Add("@time_to", SqlDbType.VarChar).Value = time_to;
                    try
                    {
                        List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            while(dr.Read())
                            {
                                Dictionary<string, object> data = new Dictionary<string, object>();
                                for(int i=0;i<dr.FieldCount;i++)
                                {
                                    data.Add(dr.GetName(i), dr[i]);
                                }
                                result.Add(data);
                            }
                        }
                        response.userinfo = result;
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }
    }
}
